<template>
  <div class="museum-creative">
    <!-- 导航栏 -->
    <div class="nav-container">
      <div class="logo">
        <span class="logo-text">文创</span>
      </div>
      <ul class="nav-menu">
        <li class="nav-item">
          <a href="/museum" class="nav-link">首页</a>
        </li>
        <li class="nav-item">
          <router-link to="/allproducts" class="nav-link">查看全部</router-link>
        </li>
        <li class="nav-item">
          <router-link to="/myorders" class="nav-link" >我的订单</router-link>
        </li>
        <li class="nav-item">
          <router-link v-if="!isLoggedIn()" to="/login" class="nav-link">登录</router-link>
          <router-link v-if="isLoggedIn()" to="/museum" class="nav-link" @click.prevent="logout">退出</router-link>
        </li>
      </ul>
    </div>

    <!-- 购物车内容 -->
    <div class="cart-container">
      <h1 class="page-title">购物车</h1>

      <!-- 购物车为空时显示 -->
      <div v-if="cartItems.length === 0" class="empty-cart">
        <div class="empty-cart-icon">🛒</div>
        <h2>您的购物车是空的</h2>
        <p>快去挑选喜欢的文创商品吧！</p>
        <RouterLink to="/museum" class="continue-shopping">继续购物</RouterLink>
      </div>

      <!-- 有商品时显示 -->
      <div v-else class="cart-content">
        <!-- 商品列表 -->
        <div class="cart-items">
          <div class="cart-header">
            <div class="col-check">
              <input type="checkbox" id="select-all" :checked="allSelected" @change="toggleSelectAll">
              <label for="select-all">全选</label>
            </div>
            <div class="col-info">商品信息</div>
            <div class="col-price">单价</div>
            <div class="col-quantity">数量</div>
            <div class="col-total">小计</div>
            <div class="col-action">操作</div>
          </div>

          <div v-for="(item, index) in cartItems" :key="index" class="cart-item">
            <div class="col-check">
              <input type="checkbox" :id="'select-item-' + index" v-model="item.selected" @change="updateSelection">
              <label :for="'select-item-' + index"></label>
            </div>
            <div class="col-info">
              <div class="product-info">
                <img :src="getImageUrl(item.productImage)" :alt="item.name" class="product-thumbnail">
                <div class="product-details">
                  <h3 class="product-name">{{ item.name }}</h3>
                  <p class="product-desc" v-if="item.specification">{{ item.specification }}</p>
                </div>
              </div>
            </div>
            <div class="col-price">¥ {{ item.price.toFixed(2) }}</div>
            <div class="col-quantity">
              <div class="quantity-controls">
                <button class="quantity-btn" @click="decreaseQuantity(index)" :disabled="item.quantity <= 1">-</button>
                <input type="number" v-model="item.quantity" min="1" class="quantity-input"  @change="handleQuantityChange(index)">
                <button class="quantity-btn" @click="increaseQuantity(index)">+</button>
              </div>
            </div>
            <div class="col-total">¥ {{ (item.price * item.quantity).toFixed(2) }}</div>
            <div class="col-action">
              <button class="remove-btn" @click="removeItem(index)">删除</button>
            </div>
          </div>
        </div>

        <!-- 购物车底部 -->
        <div class="cart-footer">
          <div class="cart-ops">
            <button class="clear-cart" @click="clearCart">清空购物车</button>
            <div class="cart-tips">
              <p>温馨提示：</p>
              <p>1. 商品价格可能随时变动，请以结算页价格为准</p>
              <p>2. 请在24小时内完成支付，否则订单将自动取消</p>
            </div>
          </div>
          <div class="cart-total">
            <div class="selected-count">
              已选 <span>{{ selectedItemsCount }}</span> 件商品
            </div>
            <div class="total-price">
              合计：<span>¥ {{ totalPrice.toFixed(2) }}</span>
            </div>
            <button class="checkout-btn" :disabled="selectedItemsCount === 0" @click="checkout">
              去结算
            </button>
          </div>
        </div>
      </div>

      <!-- 猜你喜欢 -->
      <div class="you-may-like">
        <h2 class="section-title">猜你喜欢</h2>
        <div class="products-grid">
          <div v-for="(product, index) in recommendedProducts" :key="index" class="product-card">
            <div class="product-image-container">
              <img :src="getImageUrl(product.image)" :alt="product.name" class="product-image">
            </div>
            <div class="product-details">
              <h3 class="product-name">{{ product.name }}</h3>
              <div class="product-price">¥ {{ product.price.toFixed(2) }}</div>
              <button class="add-to-cart" @click.stop="addToCart(product)">
                <span class="icon">+</span>
                加入购物车
              </button>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, reactive, h } from 'vue';
import { useRouter } from 'vue-router';
import { ElMessage, ElMessageBox } from 'element-plus';
import * as api from '@/assets/js/api.js';
import axios from 'axios';
import { ElForm, ElFormItem, ElInput } from 'element-plus';

const router = useRouter();


// 购物车商品
const cartItems = ref([]);
// 所有商品数据，用于推荐
const allProducts = ref([]);
// 推荐商品
const recommendedProducts = ref([]);

// 页面加载时自动请求推荐商品并加载购物车
onMounted(async () => {
  await CartItems();
  await fetchRecommendedProducts();
});

// 获取购物车商品
async function CartItems() {
  const cartitem = {
    userId: Number(localStorage.getItem('userId')),
  };

  const result = await api.getCartItems(cartitem);
  console.log(result.data);  // 打印数据，检查是否获取到正确的商品

  if (result.code === 200 && result.data) {
    cartItems.value = result.data;  // 确保将数据赋值给 cartItems
  } else {
    console.log('没有获取到购物车数据');
  }
}

// 获取推荐商品
async function fetchRecommendedProducts() {
  try {
    const result = await api.product();
    if (result.code === 200 && result.data) {
      allProducts.value = result.data;
      // 随机选择4个商品作为推荐
      const shuffled = [...allProducts.value].sort(() => 0.5 - Math.random());
      recommendedProducts.value = shuffled.slice(0, 4);
    }
  } catch (error) {
    console.error('获取推荐商品失败:', error);
  }
}

// 获取图片完整URL
function getImageUrl(imagePath) {
  return `http://localhost:8080${imagePath}`;
}

// 检查用户是否已登录
function isLoggedIn() {
  return localStorage.getItem('userId');
}

// 退出登录
async function logout() {
  try {
    const result = await api.out();
    if (result.data === "退出成功") {
      localStorage.clear();
      router.push('/login');
    }
  } catch (error) {
    console.error('退出失败:', error);
  }
}

// 所有商品是否全选
const allSelected = computed(() => {
  return cartItems.value.length > 0 && cartItems.value.every(item => item.selected);
});

// 已选商品数量
const selectedItemsCount = computed(() => {
  return cartItems.value.filter(item => item.selected).length;
});

// 已选商品总价
const totalPrice = computed(() => {
  return cartItems.value
    .filter(item => item.selected)
    .reduce((total, item) => total + (item.price * item.quantity), 0);
});

// 全选/取消全选
function toggleSelectAll(event) {
  const isChecked = event.target.checked;
  cartItems.value.forEach(item => {
    item.selected = isChecked;
  });
  saveCartItems();
}

// 更新选择状态
function updateSelection() {
  saveCartItems();
}

// 增加商品数量
function increaseQuantity(index) {
  cartItems.value[index].quantity++;
  updateItemTotal(index);
}

// 减少商品数量
function decreaseQuantity(index) {
  if (cartItems.value[index].quantity > 1) {
    cartItems.value[index].quantity--;
    updateItemTotal(index);
  }
}


async function handleQuantityChange(index) {
  // 更新前端小计显示
  updateItemTotal(index);

  const item = cartItems.value[index];
  const id = item.id;
  const quantity = item.quantity;

  try {
    const res = await api.updateCartItem(id, quantity);
    console.log('更新成功:', res.message);
  } catch (error) {
    console.error('更新失败:', error);
  }
}

// 更新商品小计
async function updateItemTotal(index) {
  // 确保数量是有效的数字且最小为1
  const quantity = parseInt(cartItems.value[index].quantity);
  cartItems.value[index].quantity = isNaN(quantity) || quantity < 1 ? 1 : quantity;
  const item = cartItems.value[index];
  const id = item.id;
  try {
    const res = await api.updateCartItem(id, quantity);
    console.log('更新成功:', res.message);
  } catch (error) {
    console.error('更新失败:', error);
  }
}

// 删除商品
function removeItem(index) {
  ElMessageBox.confirm('确定要从购物车中删除此商品吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning' 
  }).then(async () => {
    const item = cartItems.value[index];
    const id = item.id;
    try {
      const res = await api.removeCartItem(id);
      console.log('删除成功:', res.message);
    } catch (error) {
      console.error('删除失败:', error);
    }
    cartItems.value.splice(index, 1);
   
    ElMessage.success('商品已从购物车中删除');
  }).catch(() => {



  });
}

// 清空购物车
function clearCart() {
  ElMessageBox.confirm('确定要清空购物车吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    const userId = Number(localStorage.getItem('userId'));
    const res = await api.clearCart(userId).then(
      (res) => {
        window.location.reload();
      }
    );
    console.log('清空成功:', res.message);
    ElMessage.success('购物车已清空');
  }).catch(() => {});
}

// 添加到购物车
async function addToCart(product) {
  if (!isLoggedIn()) {
    ElMessage.warning('请先登录后再添加商品到购物车');
    router.push('/login');
    return;
  }

  const userId = Number(localStorage.getItem('userId'));
  const cartItem = {
    userId: userId,
    productId: product.id,
    productName: product.name,
    productImage: product.image,
    price: product.price,
    quantity: 1, // 默认添加一个
    selected: true
  };

  try {
    // 调用后端 API 添加商品到购物车
    const result = await api.addToCart(cartItem);

    if (result.code === 200) {
      // 提示添加成功
      ElMessage.success(`${product.name} 已添加到购物车`);
    } else {
      ElMessage.error('添加到购物车失败');
    }
  } catch (error) {
    console.error('添加到购物车失败:', error);
    ElMessage.error('添加到购物车失败，请稍后重试');
  }
}

// 将表单引用移到顶层作用域
const addressFormRef = ref(null);

async function checkout() {
  if (selectedItemsCount.value === 0) {
    ElMessage.warning('请至少选择一件商品');
    return;
  }
  
  // 添加地址表单数据
  const addressForm = reactive({
    address: '',
    phone: '',
    remark: '',
    paymentMethod: '支付宝' // 默认选择支付宝支付
  });
  
  // 地址验证规则
  const addressRules = {
    address: [{ required: true, message: '请输入收货地址', trigger: 'blur' }],
    phone: [
      { required: true, message: '请输入联系电话', trigger: 'blur' },
      { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
    ],
    paymentMethod: [{ required: true, message: '请选择支付方式', trigger: 'change' }]
  };
  
  // 不再需要在这里创建表单引用
  // const addressFormRef = ref(null);
  
  // 使用 ElMessageBox 显示地址填写表单
  try {
    await ElMessageBox.confirm(
      h('div', { style: 'width: 100%' }, [
        h('h3', { style: 'margin-bottom: 15px' }, '请填写收货信息'),
        h(ElForm, {
          ref: addressFormRef,
          model: addressForm,
          rules: addressRules,
          labelWidth: '80px',
          style: 'margin: 10px 0'
        }, {
          default: () => [
            h(ElFormItem, { label: '收货地址', prop: 'address' }, {
              default: () => h(ElInput, {
                modelValue: addressForm.address,
                'onUpdate:modelValue': (val) => addressForm.address = val,
                placeholder: '请输入详细收货地址'
              })
            }),
            h(ElFormItem, { label: '联系电话', prop: 'phone' }, {
              default: () => h(ElInput, {
                modelValue: addressForm.phone,
                'onUpdate:modelValue': (val) => addressForm.phone = val,
                placeholder: '请输入联系电话'
              })
            }),
            
            h(ElFormItem, { label: '备注信息', prop: 'remark' }, {
              default: () => h(ElInput, {
                modelValue: addressForm.remark,
                'onUpdate:modelValue': (val) => addressForm.remark = val,
                type: 'textarea',
                placeholder: '可选填写备注信息'
              })
            })
          ]
        })
      ]),
      {
        title: '填写收货信息',
        confirmButtonText: '确认提交',
        cancelButtonText: '取消',
        customClass: 'address-form-dialog',
        beforeClose: (action, instance, done) => {
          if (action === 'confirm') {
            // 使用更安全的方式处理表单验证
            if (addressFormRef.value && typeof addressFormRef.value.validate === 'function') {
              addressFormRef.value.validate((valid) => {
                if (valid) {
                  done();
                } else {
                  // 验证失败，不关闭对话框
                  ElMessage.warning('请填写必要的信息');
                }
              });
            } else {
              // 如果无法验证，直接关闭并给出提示
              ElMessage.warning('无法验证表单，将直接提交');
              done();
            }
          } else {
            done();
          }
        }
      }
    );
    
    // 表单验证通过，创建订单
    const order = {
      userId: Number(localStorage.getItem('userId')),
      address: addressForm.address,
      phone: addressForm.phone,
      remark: addressForm.remark,
    };

    // 调用创建订单的API
    const result = await api.createOrder(order);
    
    if (result.code === 200) {
      // 提示结算成功
      ElMessage.success('订单已提交，即将为您跳转到支付页面');
      
      // 获取订单号
      const orderNumber = result.data.number;
      
      // 跳转到支付页面或订单详情页
      router.push(`/payment?orderNumber=${orderNumber}`);
    } else {
      ElMessage.error('订单创建失败: ' + result.msg);
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('结算失败:', error);
      ElMessage.error('结算失败，请稍后重试');
    }
  }
}
</script>

<style>
/* 引入公共CSS文件 */
@import '../../assets/css/museum-product.css';
/* 引入购物车专用CSS文件 */
@import '../../assets/css/shopping-cart.css';
</style>
